/*
 * ImageHandler.java
 *
 * Created on 4 September 2006, 2:39
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package fasea.index.filehandler;

import fasea.ui.utils.ImageControl;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Document;

/**
 *
 * @author gvasil
 */
class ImageHandler extends FileHandler {

    public Document getTypedDocument(File file) throws FileHandlerException {
        String path = null, filename = null, parentFolderName = null;
        org.apache.lucene.document.Document doc = createDefaultLuceneDocument(file);
        try {
            path = file.getCanonicalPath();
            filename = path.substring(path.lastIndexOf(File.separatorChar) + 1);
            parentFolderName = path.substring(0, path.lastIndexOf(File.separatorChar));
            parentFolderName = parentFolderName.substring(parentFolderName.lastIndexOf(File.separatorChar) + 1);

            BufferedImage img = ImageIO.read(new File(path));

            if (img == null) {
                throw new FileHandlerException("Error decoding image.");
            }

            int width = img.getWidth();
            int height = img.getHeight();

            doc.add(new Field("content", filename + " " +parentFolderName, Field.Store.NO,
                    Field.Index.ANALYZED, Field.TermVector.YES));

            doc.add(new Field("width", String.valueOf(width),
                    Field.Store.YES, Field.Index.NOT_ANALYZED));
            doc.add(new Field("height", String.valueOf(height),
                    Field.Store.YES, Field.Index.NOT_ANALYZED));
            byte[] bytes = ImageControl.getImageControl().createImageThumbnail(img);
            if (bytes != null) {
                doc.add(new Field("thumbnail", bytes));
            }
        } catch (IOException e) {
            throw new FileHandlerException(e.getMessage());
        } catch (IllegalArgumentException e) {
            throw new FileHandlerException(e.getMessage());
        }
        return doc;
    }
}
